package cn.alone.org.service.impl;

import cn.alone.basic.service.impl.BaseServiceImpl;
import cn.alone.basic.util.MD5Utils;
import cn.alone.basic.util.StrUtils;
import cn.alone.org.domain.Employee;
import cn.alone.org.mapper.EmployeeMapper;
import cn.alone.org.service.IEmployeeService;
import cn.alone.user.domain.Logininfo;
import cn.alone.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 员工业务层实现层
 * @author lanan
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void add(Employee employee) {
        //初始化Employee的必要字段
        initEmployee(employee);
        //拷贝一个logininfo
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        /*0代表后台员工*/
        logininfo.setType(0);
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        //使用盐值加密
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }


    @Override
    public Employee loadByLogininfoId(Long id) {
        return employeeMapper.loadByLogininfoId(id);
    }
}
